//
//  GKNovelView.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2019/9/10.
//  Copyright © 2019 wangws1990. All rights reserved.
//

import UIKit

class GKNovelView: UIView {

    var _content:NSAttributedString!;
    var contentFrame :CTFrame!
    var content:NSAttributedString{
        set{
            _content = newValue;
            self.setNeedsDisplay()
        }get{
            return _content ?? self.getAtt();
        }
    }
    override func layoutSubviews() {
        super .layoutSubviews();
        let setterRef:CTFramesetter = CTFramesetterCreateWithAttributedString(self.content);
        let pathRef :CGPath = CGPath(rect: self.bounds,transform: nil)
        let frameRef :CTFrame = CTFramesetterCreateFrame(setterRef, CFRangeMake(0, 0), pathRef, nil);
        self.contentFrame = frameRef;
    }
    override func draw(_ rect: CGRect) {
        if self.contentFrame == nil {
            return;
        }
        let ctx : CGContext = UIGraphicsGetCurrentContext()!;
        ctx.textMatrix = .identity;
        ctx.translateBy(x: 0, y: self.bounds.height)
        ctx.scaleBy(x: 1, y: -1)
        CTFrameDraw(self.contentFrame, ctx);
    }
    func getAtt() -> NSAttributedString {
        let title:String = "数据加载中..."
        let attr:NSMutableAttributedString = NSMutableAttributedString.init(string:title);
        let ranges = NSRange.init(location:0, length:title.count);
        attr.addAttribute(.font, value: UIFont.systemFont(ofSize: 18), range: ranges);
        attr.addAttribute(.foregroundColor, value: UIColor.init(hex: "999999"), range: ranges);
        
        let paragraphStyle :NSMutableParagraphStyle = NSMutableParagraphStyle.init();
        paragraphStyle.alignment = .center;
        attr.addAttribute(.paragraphStyle, value: paragraphStyle, range: ranges);
        return attr
    }

}
